package com.tinem.platform.service.task.job.day;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Data
@Component
@Configurable
@ConfigurationProperties(prefix = "job.day.elasticsearch.clear")
public class ElasticsearchClear {

    List<Config> configs;

    @Scheduled(cron = "0 0 1 * * ?")
    public void execute(){
        Date day = new Date();
        if(CollUtil.isEmpty(configs)){
            return;
        }
        configs.forEach(config -> {
            try {
                Date clearDay = DateUtil.offset(day, DateField.DAY_OF_YEAR, (int) config.getInterval().toDays());
                String url = StrUtil.format(config.getElasticsearchUrl(),new HashMap(){{
                    put("date",DateUtil.format(clearDay,config.getFormat()));
                }});
                HttpResponse response = HttpRequest.delete(url).execute();
                log.info("url:{},res code:{} res body:{}",url,response.getStatus(),response.body());
            }catch (Exception e){
                log.error(JSONObject.toJSONString(config),e);
            }
        });
    }

    @Data
    public static class Config{
        Duration interval;
        String elasticsearchUrl;
        String format;
    }
}
